package com.dycx.user.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dycx.user.mapper.CreditRecordMapper;
import com.dycx.user.dto.CreditRecordDTO;
import com.dycx.user.entity.CreditRecordDO;
import com.dycx.user.entity.UserInfoDO;
import com.dycx.user.enums.CreditRecordEnum;
import com.dycx.user.service.CreditRecordService;
import com.dycx.user.service.UserInfoService;
import com.dycx.user.vo.CreditRecordVO;
import com.dycx.user.vo.UserInfoVO;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@AllArgsConstructor
public class CreditRecordImpl extends ServiceImpl<CreditRecordMapper, CreditRecordDO> implements CreditRecordService {

    private CreditRecordMapper creditRecordMapper;
    private UserInfoService userInfoService;

    /**
     * 添加
     *
     * @param creditRecordDto
     * @return
     */
    @Override
    public Boolean updateCredit(CreditRecordDTO creditRecordDto) {
        UserInfoVO userInfoVo = userInfoService.load(creditRecordDto.getUid());
        if (ObjectUtil.isEmpty(userInfoVo)) {
            throw new RuntimeException("用户不存在，积分操作失败");
        }

        Integer currentCredit = userInfoVo.getCredit() + creditRecordDto.getNum();
        if (currentCredit < 0) {
            throw new RuntimeException("操作后积分数小于0，积分操作失败");
        }

        CreditRecordDO creditRecord = BeanUtil.toBean(creditRecordDto, CreditRecordDO.class);
        creditRecord.setCurrentCredit(currentCredit);
        if (!this.save(creditRecord)) {
            throw new RuntimeException("积分记录添加失败");
        }

        LambdaQueryWrapper<UserInfoDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserInfoDO::getUid, creditRecordDto.getUid());

        UserInfoDO userInfoDO = new UserInfoDO();
        userInfoDO.setCredit(currentCredit);
        if (!userInfoService.update(userInfoDO, queryWrapper)) {
            throw new RuntimeException("修改用户剩余积分失败");
        }

        return true;
    }


    @Override
    public Page<CreditRecordVO> getPage(CreditRecordDTO creditRecordDTO) {
        Page<CreditRecordVO> page = new Page<>(creditRecordDTO.getPageIndex(), creditRecordDTO.getPageSize());  // 查询第1页，每页返回5条

        Page<CreditRecordVO> pageData = creditRecordMapper.getPage(page, creditRecordDTO);

        List<CreditRecordVO> dataList = pageData.getRecords();
        dataList.forEach(item -> {
            CreditRecordEnum creditRecordEnum = CreditRecordEnum.getCode(item.getType());
            item.setTypeName(creditRecordEnum.getName());
            item.setTypeStyle(creditRecordEnum.getStyle());
        });

        return pageData.setRecords(dataList);
    }


}
